/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: FinancePurchaseActivity.java
 *   @Date: 19-3-11 下午4:44
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.finance.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

import java.math.BigDecimal;

import io.bhex.app.R;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.finance.presenter.FinancePurchasePresenter;
import io.bhex.app.utils.ActivityCache;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.app.view.PointLengthFilter;
import io.bhex.app.view.TopBar;
import io.bhex.app.web.ui.WebActivity;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.Urls;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.finance.bean.FinanceBean;

public class FinancePurchaseActivity extends BaseActivity<FinancePurchasePresenter,FinancePurchasePresenter.FinancePurchaseUI> implements FinancePurchasePresenter.FinancePurchaseUI, View.OnClickListener {
    private TopBar topBar;
    private FinanceBean financeBean;
    private TextInputLayout amountTextInputLayout;
    private TextInputEditText amountTextInputEt;
    private CheckBox agreeCb;
    private View agreeFinance;
    private Button btnPurchase;
    private PointLengthFilter amountPointFilter;
    private String productId;
    private View btnClear;
    private String mUserLastLimit="";
    private int tradeScale = AppData.Config.DIGIT_DEFAULT_VALUE;

    @Override
    protected int getContentView() {
        return R.layout.activity_finance_purchase_activity;
    }

    @Override
    protected FinancePurchasePresenter createPresenter() {
        return new FinancePurchasePresenter();
    }

    @Override
    protected FinancePurchasePresenter.FinancePurchaseUI getUI() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityCache.getInstance().addFinanceActivity(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCache.getInstance().removeFinanceActivity(this);
    }

    @Override
    protected void initView() {
        super.initView();
        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        Intent intent = getIntent();
        if (intent != null) {
            productId = intent.getStringExtra("productId");

        }
        amountTextInputLayout = viewFinder.find(R.id.purchase_amount_il);
        amountTextInputEt = viewFinder.find(R.id.purchase_amount_iet);
        btnClear = viewFinder.find(R.id.input_clear);
        agreeCb = viewFinder.find(R.id.agreement);
        agreeFinance = viewFinder.find(R.id.agreement_finance);
        btnPurchase = viewFinder.find(R.id.btn_purchase);
        amountPointFilter = new PointLengthFilter();
        amountPointFilter.setDecimalLength(2);
        amountTextInputEt.setFilters(new InputFilter[]{amountPointFilter});
        if (financeBean != null) {
//            String perIncrease = NumberUtils.roundFormatDown(String.valueOf(Math.pow(0.1, financeBean.getTradeScale())),financeBean.getTradeScale());
            int tradeScale = NumberUtils.calNumerCount(this, financeBean.getTradeScale());
            amountPointFilter.setDecimalLength(tradeScale);
        }
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.agreement_finance).setOnClickListener(this);
        viewFinder.find(R.id.btn_recharge).setOnClickListener(this);
        viewFinder.find(R.id.btn_purchase).setOnClickListener(this);
        viewFinder.find(R.id.input_clear).setOnClickListener(this);
        amountTextInputEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    btnPurchase.setEnabled(false);
                    btnClear.setVisibility(View.GONE);
                }else{
                    btnPurchase.setEnabled(true);
                    amountTextInputLayout.setErrorEnabled(false);
                    btnClear.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(productId)) {
            getPresenter().getFinanceDetail(productId);
        }
    }

    @Override
    protected boolean isNeedLogin() {
        return true;
    }

    @Override
    public void showFinanceDetail(FinanceBean response, String userLastLimit) {
        if (response != null) {
            financeBean = response;
            mUserLastLimit = userLastLimit;
            tradeScale = NumberUtils.calNumerCount(this, financeBean.getTradeScale());
            viewFinder.textView(R.id.surplusAmount).setText(getString(R.string.string_finance_surplus_amount)+" "+NumberUtils.roundFormatDown(response.getDailyLastLimit(),tradeScale)+" "+response.getToken());
            viewFinder.textView(R.id.purchase_amount_title).setText(getString(R.string.string_purchase_amount)+"("+response.getToken()+")");
            amountPointFilter.setDecimalLength(tradeScale);
//            String perIncrease = NumberUtils.roundFormatDown(String.valueOf(Math.pow(0.1, tradeScale)),tradeScale);
            amountTextInputEt.setHint(getString(R.string.string_finance_purchase_amount_hint,financeBean.getTradeMinAmount(),financeBean.getToken(),financeBean.getTradeScale(),financeBean.getToken()));
        }
    }

    @Override
    public void updateAssettByToken(String tokenId, String free) {
        if (financeBean != null) {
            if (financeBean.getToken().equals(tokenId)) {
                viewFinder.textView(R.id.avaliable_amount).setText(getString(R.string.string_finance_avaliable_amount)+" "+NumberUtils.roundFormatDown(TextUtils.isEmpty(free)?"0.00":free, AppData.Config.DIGIT_DEFAULT_VALUE)+" "+tokenId);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.input_clear:
                amountTextInputEt.setText("");
                break;
            case R.id.btn_recharge:
                if (UserInfo.isLogin(this,AppData.INTENT.LOGIN_CALLER_TRADE)) {
                    if(financeBean != null)
                        IntentUtils.goMyAssetTokenDeposit(financeBean.getToken(),this);
                }
                break;
            case R.id.agreement_finance:
//                agreeCb.setChecked(!agreeCb.isChecked());
                WebActivity.runActivity(this,getResources().getString(R.string.string_finance_agreement),Urls.H5_URL_FINANCE_SERVICE);
                break;

            case R.id.btn_purchase:
                if (UserInfo.isLogin(this,AppData.INTENT.LOGIN_CALLER_TRADE)) {
                    if (financeBean != null) {

                        String amount = amountTextInputEt.getText().toString().trim();
                        if (TextUtils.isEmpty(amount)) {
                            amountTextInputLayout.setError(getString(R.string.string_input_please)+getString(R.string.string_purchase_amount));
                            return;
                        }
                        String tradeMinAmount = financeBean.getTradeMinAmount();
                        if (NumberUtils.sub(amount,tradeMinAmount)<0) {
//                            ToastUtils.showLong(getString(R.string.string_finance_no_less_min_trade_amount_format,tradeMinAmount,financeBean.getToken()));
                            amountTextInputLayout.setError(getString(R.string.string_finance_no_less_min_trade_amount_format,tradeMinAmount,financeBean.getToken()));
                            return;
                        }
                        String userLimit = financeBean.getUserLimit();
                        if (NumberUtils.sub(amount,userLimit)>0||NumberUtils.sub(amount,mUserLastLimit)>0) {
//                            ToastUtils.showLong(getString(R.string.string_finance_user_limit_trade_amount_format,userLimit,financeBean.getToken()));
                            amountTextInputLayout.setError(getString(R.string.string_finance_user_limit_trade_amount_format,userLimit,financeBean.getToken(),NumberUtils.roundFormatDown(mUserLastLimit,tradeScale),financeBean.getToken()));
                            return;
                        }
                        String tradeScale = financeBean.getTradeScale();
                        if (new BigDecimal(amount).remainder(new BigDecimal(tradeScale)).compareTo(BigDecimal.ZERO)!=0) {
                            amountTextInputLayout.setError(getString(R.string.string_finance_input_trade_amount_must_integer_multiple_format,tradeScale));
                            return;
                        }

                        if (!agreeCb.isChecked()) {
                            ToastUtils.showLong(this,getString(R.string.string_read_agree_finance_agreement_please));
                            return;
                        }
                        getPresenter().purchase(financeBean,amount);
                    }else{
                        ToastUtils.showLong(this,getString(R.string.string_data_exception));
                    }
                }
                break;
        }
    }
}
